package com.eshop.modules.system.service.impl;

import java.lang.invoke.SerializedLambda;
import com.eshop.exception.BadRequestException;
import com.eshop.modules.system.domain.RolesDepts;
import com.eshop.modules.system.domain.Job;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import java.util.Set;
import java.util.HashMap;
import java.util.Collection;
import org.springframework.util.CollectionUtils;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.function.Function;
import java.util.LinkedHashSet;
import java.io.IOException;
import java.util.Iterator;
import com.eshop.utils.FileUtil;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.eshop.common.utils.QueryHelpPlus;
import com.eshop.modules.system.service.dto.DeptDto;
import java.util.LinkedHashMap;
import java.util.List;
import com.github.pagehelper.PageInfo;
import java.util.Map;
import org.springframework.data.domain.Pageable;
import com.eshop.modules.system.service.dto.DeptQueryCriteria;
import com.eshop.modules.system.service.mapper.RolesDeptsMapper;
import com.eshop.modules.system.service.mapper.JobMapper;
import com.eshop.dozer.service.IGenerator;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import com.eshop.modules.system.service.DeptService;
import com.eshop.modules.system.domain.Dept;
import com.eshop.modules.system.service.mapper.DeptMapper;
import com.eshop.common.service.impl.BaseServiceImpl;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = { Exception.class })
public class DeptServiceImpl extends BaseServiceImpl<DeptMapper, Dept> implements DeptService
{
    private final IGenerator generator;
    private final DeptMapper deptMapper;
    private final JobMapper jobMapper;
    private final RolesDeptsMapper rolesDeptsMapper;
    
    public Map<String, Object> queryAll(final DeptQueryCriteria criteria, final Pageable pageable) {
        this.getPage(pageable);
        final PageInfo<Dept> page = (PageInfo<Dept>)new PageInfo((List)this.queryAll(criteria));
        final Map<String, Object> map = new LinkedHashMap<String, Object>(2);
        map.put("content", this.generator.convert(page.getList(), (Class)DeptDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }
    
    public List<Dept> queryAll(final DeptQueryCriteria criteria) {
        return (List<Dept>)((DeptMapper)this.baseMapper).selectList(QueryHelpPlus.getPredicate(Dept.class, criteria));
    }
    
    public void download(final List<DeptDto> all, final HttpServletResponse response) throws IOException {
        final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (final DeptDto dept : all) {
            final Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("名称", dept.getName());
            map.put("上级部门", dept.getPid());
            map.put("状态", dept.getEnabled());
            map.put("创建日期", dept.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel((List)list, response);
    }
    
    public List<Dept> findByPid(final long pid) {
        final DeptQueryCriteria criteria = new DeptQueryCriteria();
        criteria.setPid(pid);
        return (List<Dept>)((DeptMapper)this.baseMapper).selectList(QueryHelpPlus.getPredicate(Dept.class, criteria));
    }
    
    public Object buildTree(final List<DeptDto> deptDtos) {
        Set<DeptDto> trees = new LinkedHashSet<DeptDto>();
        final Set<DeptDto> depts = new LinkedHashSet<DeptDto>();
        final List<String> deptNames = deptDtos.stream().map(DeptDto::getName).collect(Collectors.toList());
        final DeptQueryCriteria criteria = new DeptQueryCriteria();
        final List<Dept> deptList = this.queryAll(criteria);
        for (final DeptDto deptDto : deptDtos) {
            boolean isChild = false;
            if ("0".equals(deptDto.getPid().toString())) {
                trees.add(deptDto);
            }
            for (final DeptDto it : deptDtos) {
                if (it.getPid().equals(deptDto.getId())) {
                    isChild = true;
                    if (deptDto.getChildren() == null) {
                        deptDto.setChildren(new ArrayList<DeptDto>());
                    }
                    deptDto.getChildren().add(it);
                }
            }
            if (isChild) {
                depts.add(deptDto);
                for (final Dept dept : deptList) {
                    if (dept.getId().equals(deptDto.getPid()) && !deptNames.contains(dept.getName())) {
                        depts.add(deptDto);
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(trees)) {
            trees = depts;
        }
        final Integer totalElements = deptDtos.size();
        final Map<String, Object> map = new HashMap<String, Object>(2);
        map.put("totalElements", totalElements);
        map.put("content", CollectionUtils.isEmpty(trees) ? deptDtos : trees);
        return map;
    }
    
    public void delDepts(final List<Long> deptIds) {
        final int jobCount = this.jobMapper.selectCount(Wrappers.<Job>lambdaQuery().in(Job::getDeptId, deptIds));
        final int roleCount = this.rolesDeptsMapper.selectCount(Wrappers.<RolesDepts>lambdaQuery().in(RolesDepts::getDeptId, deptIds));
        if (jobCount > 0) {
            throw new BadRequestException("所选部门中存在与岗位关联，请取消关联后再试");
        }
        if (roleCount > 0) {
            throw new BadRequestException("所选部门中存在与角色关联，请取消关联后再试");
        }
        this.removeByIds(deptIds);
    }
    
    public Set<Dept> findByRoleIds(final Long id) {
        return this.deptMapper.findDeptByRoleId(id);
    }
    
    public DeptServiceImpl(final IGenerator generator, final DeptMapper deptMapper, final JobMapper jobMapper, final RolesDeptsMapper rolesDeptsMapper) {
        this.generator = generator;
        this.deptMapper = deptMapper;
        this.jobMapper = jobMapper;
        this.rolesDeptsMapper = rolesDeptsMapper;
    }
}
